<?php

class MailConversationController extends GxController {

    public function filters() {
        return array('rights');
    }

    public function actionsendMailTouser() {
        if (isset($_POST['msgval'])) {
            $subject = ContactAdmin::gettrainerMailSubject($_POST['from_user']);
            $model = new ContactAdmin();
            $model->setAttribute('subject', $subject);
            $model->setAttribute('query', $_POST['msgval']);
            $model->setAttribute('backend_user_id', Message::ADMIN_ID);
            $model->setAttribute('from_users_id', $_POST['from_user']);
            $model->setAttribute('created', SkillConfig::CreateDateTime());
            $model->setAttribute('is_read', SkillConfig::STATUS_DEACTIVE);
            $model->save(FALSE);
            $trainer = Users::getFrontEndUser($_POST['from_user']);
            $mailmodel = EmailTemplate::model()->findByPk(Message::ADMIN_RESPONSE_TO_TRAINER);
            $userText = $mailmodel->body;
            $mailbody = array('value' => $userText, 'type' => 'raw');
            $userName = (!empty($trainer) ? $trainer->first_name : $trainer->user->username);
            $mailto = $trainer->user->username;
            $inboxLink = '<a href=' . SITE_URL . 'mailConversation/inbox/' . '>View Inbox</a>';
            $arrayFind = array('[username]', '[activation_link]');
            $arrayReplace = array($userName, $inboxLink);
            $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
            $mailtemp = Template::model()->findByPk($mailmodel->template_id);
            $subject = $mailmodel->subject;
            $body = $this->renderPartial('/mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
            try {
                SkillSendMail::SendMail($mailto, $subject, $body);
                $result = 'success';
            } catch (Exception $e) {
                $result = $e;
                exit;
            }
        }
        if ($result == 'success') {
            echo 'success';
        }
        Yii::app()->end();
    }

    public function actionInbox() {
        $criteria = new CDbCriteria;
        $criteria->group = 'from_users_id';
        $criteria->condition = 'backend_user_id	 = ' . Message::ADMIN_ID;
        $inboxAll = ContactAdmin::model()->findAll($criteria);
        $this->render('inbox', array('userDetails' => $inboxAll));
    }

    public function actiongettrainerconversion() {
        $this->layout = FALSE;
        $criteria = new CDbCriteria;
        $criteria->condition = 'from_users_id = ' . $_POST['from_user'];
        $dataByUser = ContactAdmin::model()->findAll($criteria);
        ContactAdmin::model()->updateAll(array('is_read' => SkillConfig::STATUS_ACTIVE), 'from_users_id = ' . $_POST['from_user']);
        $this->render('_view', array('dataByUser' => $dataByUser));
    }

}